<template>
  <a-card :bordered="false">
    <a-table
      ref="table"
      size="middle"
      bordered
      rowKey="id"
      :pagination="ipagination"
      :columns="columns"
      :dataSource="dataSource"
      :loading="loading"
      :rowSelection="{selectedRowKeys: computedKeys, onChange: onSelectChange}"
      @change="handleTableChange">
    </a-table>
  </a-card>
</template>

<script>

  import { YcListMixin } from '@/mixins/YcListMixin'
  import YchConstant from "@/api/YchConstant";

  export default {
    name: 'SelectRelationPosition',
    mixins: [YcListMixin],
    props: {
      value: {
        type: Array,
        required: true
      },
      currentRelationId: {
        type: String,
        default: null
      },
      currentRelationName: {
        type: String,
        default: null
      }
    },
    data () {
      return {
        all: false,
        columns: [
          {
            title: this.$t('m.system.position.entity.positionName'),
            align: 'center',
            dataIndex: 'name'
          },
          {
            title: this.$t('m.system.position.entity.positionCode'),
            align: 'center',
            dataIndex: 'positionCode'
          },
        ],
        url: {
          list: YchConstant.PREFIX_BPM + '/bpm-back/processSelectRest/getPositionListByPage/v1',
        }
      }
    },
    computed: {
      computedKeys () {
        if (this.currentRelationId) {
          return this.value.filter(item => item.id.startsWith(this.currentRelationId + '#')).map(item => item.id.substring(item.id.indexOf('#') + 1))
        } else {
          return []
        }
      }
    },
    watch: {
      currentRelationId: {
        handler (value) {
          if (value) {
            const id = value + '#all'
            const checkData = this.value.find(item => item.id == id)
            this.all = !!checkData
          }
        },
        immediate: true
      }
    },
    methods: {
      onSelectChange (selectedRowKeys, selectedRows) {
        const oldKeys = this.computedKeys
        let data = this.value.filter(item => !item.id.startsWith(this.currentRelationId + '#') || selectedRowKeys.indexOf(item.id.substring(item.id.indexOf('#') + 1)) != -1)//原来剩下的
        const addIds = selectedRowKeys.filter(id => oldKeys.indexOf(id) == -1)//新增的
        selectedRows.forEach(item => {
          if (addIds.indexOf(item.id) != -1) {
            data.push({
              id: this.currentRelationId + '#' + item.id,
              name: this.currentRelationName + '#' + item.name
            })
          }
        })
        if(addIds.length>0){
          data = data.filter(item => item.id!=this.currentRelationId);
        }
        this.$emit('input', data)
      },
    }
  }
</script>
